import 'package:aero_frisbee/app/model/af_home_user_model/af_home_user_model.dart';
import 'package:aero_frisbee/app/model/af_post_comment_model/af_post_comment_model.dart';
import 'package:aero_frisbee/app/model/local_post_model/local_post_model.dart';
import 'package:aero_frisbee/app/state/af_app_state_ext.dart';
import 'package:aero_frisbee/app_route.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/core/tools/af_log_manager.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/modues/home/view_model/af_home_view_model.dart';
import 'package:aero_frisbee/pages/modues/message/pages/followed/view_model/af_followed_list_view_model.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:aero_frisbee/pages/modues/post/af_profile_detail_screen/views/af_more_action_sheet.dart';
import 'package:aero_frisbee/pages/modues/videos/views/post_gift_sheet_view.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:go_router/go_router.dart';

import 'af_profile_detail_screen/views/af_report_options_sheet.dart';
import 'view_model/af_post_detail_view_model.dart';

class AfPostDetailScreen extends ConsumerStatefulWidget {
  const AfPostDetailScreen({super.key, required this.item});
  final LocalPostModel item;
  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AfPostDetailScreenState();
}

class _AfPostDetailScreenState extends ConsumerState<AfPostDetailScreen> {
  AfHomeUserModel? get homeUser => widget.item.cacheBind?.homeUser;

  final _textController = TextEditingController();
  @override
  Widget build(BuildContext context) {
    final commentList = ref
        .watch(afPostCommentListServiceProvider(postId: '${widget.item.uid}'));
    final _ = ref.watch(afCreateCommentServiceProvider);
    final userInfo = ref
        .watch(getUserInfoFutureProvider(
            userId: widget.item.cacheBind?.homeUser?.userId ?? ''))
        .maybeWhen(
          orElse: () => null,
          data: (data) => data,
        );

    ref.listen(unfriendServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.invalidate(getUserInfoFutureProvider);
      }
    });
    ref.listen(unblockServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        ref.invalidate(getBlockListFutureProvider);
        ref.invalidate(getUserInfoFutureProvider);
      }
    });
    ref.listen(reportServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        "Report Success".toast();
      }
    });

    return Scaffold(
      backgroundColor: const Color(0xffF6F7F8),
      appBar: AppBar(
        backgroundColor: Colors.white,
        leadingWidth: 40,
        leading: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Align(
            alignment: Alignment.centerLeft,
            child: Padding(
              padding: const EdgeInsets.only(left: 16, right: 0, bottom: 3),
              child: Assets.icons.iconMineBack.image(),
            ),
          ),
        ),
        title: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            context.pushNamed(RouteUri.profileDetailScreen, extra: widget.item);
          },
          child: Row(
            children: [
              Stack(
                children: [
                  SizedBox(
                    height: 36,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(18),
                      child: AspectRatio(
                        aspectRatio: 1,
                        child: CachedNetworkImage(
                          imageUrl: homeUser?.avatar ?? '',
                          fit: BoxFit.fill,
                          placeholder: (context, url) => const Material(
                            color: Color(0xffF2F5F9),
                            child: Center(
                              child: SizedBox(
                                width: 25,
                                height: 25,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  color: Color(0xffADADAD),
                                  backgroundColor: Colors.white,
                                ),
                              ),
                            ),
                          ),
                          errorWidget: (context, url, error) =>
                              const CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Color(0xffADADAD),
                            backgroundColor: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                  Positioned(
                    bottom: 0,
                    right: 0,
                    child: Visibility(
                      visible: userInfo?.isFriend != true,
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          ref
                              .read(addFriendServiceProvider.notifier)
                              .addFriend(userId: userInfo?.userId ?? '');
                        },
                        child: Container(
                          decoration: const BoxDecoration(),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 2,
                              vertical: 0,
                            ),
                            child: Assets.icons.iconProfileFollowBtn
                                .image(width: 15),
                          ),
                        ),
                      ),
                    ),
                  )
                ],
              ),
              const SizedBox(
                width: 10,
              ),
              Flexible(
                child: Text(
                  homeUser?.nickname ?? '',
                  style: const TextStyle(
                    color: Color(0xff000000),
                    fontWeight: FontWeight.normal,
                    fontSize: 16,
                  ),
                  textAlign: TextAlign.left,
                  overflow: TextOverflow.ellipsis,
                  maxLines: 1,
                ),
              )
            ],
          ),
        ),
        actions: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              showAfMoreActionSheet(
                context,
                isFriend: userInfo?.isFriend == true,
                isBlock: userInfo?.isBlock == true,
                onFollowClick: () {
                  if (userInfo?.isFriend == true) {
                    ref
                        .read(unfriendServiceProvider.notifier)
                        .unfriend(userId: userInfo?.userId ?? '');
                  } else {
                    ref
                        .read(addFriendServiceProvider.notifier)
                        .addFriend(userId: userInfo?.userId ?? '');
                  }
                },
                onBlackClick: () {
                  if (userInfo?.isBlock == true) {
                    ref
                        .read(unblockServiceProvider.notifier)
                        .unblock(broadcasterId: userInfo?.userId ?? '');
                  } else {
                    ref
                        .read(blockServiceProvider.notifier)
                        .block(broadcasterId: userInfo?.userId ?? '');
                  }
                },
                onReportClick: () {
                  showAfReportOptionsSheet(
                    context,
                    onReportClick: (report) {
                      ref.read(reportServiceProvider.notifier).report(
                          complainSub: report, userId: userInfo?.userId ?? '');
                    },
                  );
                },
              );
            },
            child: Padding(
              padding:
                  const EdgeInsets.only(right: 20, left: 0, top: 5, bottom: 5),
              child: Assets.icons.iconMore.image(width: 28),
            ),
          ),
        ],
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
        child: Column(
          children: [
            Expanded(
              child: CustomScrollView(
                slivers: <Widget>[
                  SliverToBoxAdapter(
                    child: PostDetailInfo(
                      item: widget.item,
                    ),
                  ),
                  const SliverToBoxAdapter(
                    child: SizedBox(
                      height: 20,
                    ),
                  ),
                  SliverToBoxAdapter(
                    child: Container(
                      decoration: const BoxDecoration(
                        color: Colors.white,
                      ),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 20, vertical: 20),
                      child: ListView.separated(
                        shrinkWrap: true,
                        physics: const NeverScrollableScrollPhysics(),
                        padding: const EdgeInsets.only(top: 20),
                        itemBuilder: (context, index) {
                          return PostCommentCell(
                            item: commentList[index],
                            onClickLike: (item) {
                              ref
                                  .read(afPostCommentListServiceProvider(
                                          postId: '${widget.item.uid}')
                                      .notifier)
                                  .toggleLike(item);
                            },
                          );
                        },
                        separatorBuilder: (context, index) => const SizedBox(
                          height: 12,
                        ),
                        itemCount: commentList.length,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              decoration: const BoxDecoration(
                color: Colors.white,
              ),
              child: Column(
                children: [
                  SizedBox(
                    height: 60,
                    child: Row(
                      children: [
                        const SizedBox(
                          width: 20,
                        ),
                        Expanded(
                          child: SizedBox(
                            height: 40,
                            child: TextField(
                              controller: _textController,
                              onChanged: (value) {
                                ref
                                    .read(
                                        afCreateCommentServiceProvider.notifier)
                                    .updateContent(value);
                              },
                              decoration: InputDecoration(
                                contentPadding: const EdgeInsets.symmetric(
                                    horizontal: 10, vertical: 0),
                                hintText: "Enter your ideas...",
                                hintStyle: TextStyle(
                                  color:
                                      const Color(0xff000000).withOpacity(0.3),
                                  fontSize: 12,
                                  fontWeight: FontWeight.w500,
                                ),
                                fillColor: const Color(0xffF8F8F8),
                                border: const OutlineInputBorder(
                                  borderSide: BorderSide.none,
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(20),
                                  ),
                                ),
                                filled: true,
                              ),
                            ),
                          ),
                        ),
                        GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            final text =
                                ref.read(afCreateCommentServiceProvider);

                            if (text.isNotEmpty) {
                              FocusManager.instance.primaryFocus?.unfocus();
                              SmartDialog.showLoading(
                                backDismiss: false,
                                builder: (_) => const Center(
                                  child: CircularProgressIndicator(),
                                ),
                              );

                              Future.delayed(const Duration(seconds: 2), () {
                                SmartDialog.dismiss();
                                ref
                                    .read(afPostCommentListServiceProvider(
                                            postId: '${widget.item.uid}')
                                        .notifier)
                                    .addComment(text);
                                _textController.text = '';
                              });
                            } else {
                              "please input your ideas".toast();
                            }
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              color: const Color(0xffDDFB6C),
                              borderRadius: BorderRadius.circular(20),
                            ),
                            margin: const EdgeInsets.symmetric(horizontal: 20),
                            padding: const EdgeInsets.symmetric(
                                vertical: 5, horizontal: 12),
                            child: const Text(
                              'Send',
                              style: TextStyle(
                                color: Color(0xff202020),
                                fontWeight: FontWeight.normal,
                                fontSize: 16,
                              ),
                              textAlign: TextAlign.center,
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: MediaQuery.of(context).padding.bottom,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _textController.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(AfPostDetailScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

class PostDetailInfo extends ConsumerWidget {
  const PostDetailInfo({
    Key? key,
    required this.item,
  }) : super(key: key);

  final LocalPostModel item;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final curPost = ref.watch(createdPostByUidProvider(uid: item.uid ?? 0));
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(right: 4),
                  child: Text(
                    item.title ?? '',
                    style: const TextStyle(
                      color: Color(0xff202020),
                      fontWeight: FontWeight.normal,
                      fontSize: 16,
                    ),
                    textAlign: TextAlign.center,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                ),
              ),
              item.markImg,
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          Text(
            item.desc ?? '',
            style: const TextStyle(
              color: Color(0xff454545),
              fontWeight: FontWeight.normal,
              fontSize: 12,
            ),
            textAlign: TextAlign.left,
          ),
          const SizedBox(
            height: 16,
          ),
          SizedBox(
            height: 120,
            child: ListView.separated(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.only(top: 0),
              itemBuilder: (context, index) {
                return ClipRRect(
                  borderRadius: BorderRadius.circular(8),
                  child: AspectRatio(
                    aspectRatio: 104 / 120,
                    child: Image.asset(
                      'assets/res/${item.imgs[index]}',
                      fit: BoxFit.cover,
                    ),
                  ),
                );
              },
              separatorBuilder: (context, index) => const SizedBox(
                width: 10,
              ),
              itemCount: item.imgs.length,
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      color: const Color(0xffDFFFE1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    padding:
                        const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
                    child: const Text(
                      'Translate',
                      style: TextStyle(
                        color: Color(0xff141414),
                        fontWeight: FontWeight.normal,
                        fontSize: 14,
                      ),
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis,
                      maxLines: 1,
                    ),
                  )
                ],
              ),
              Row(
                children: [
                  PostMenuItem(
                    icon: Assets.icons.iconPostMsg.image(),
                    title: 'Chat',
                    onTap: () {
                      AFLogPvManger.stat(page: AFLogPages.tabChat);
                      context.pushNamed(RouteUri.messageDetai, queryParams: {
                        "userId": curPost.cacheBind?.homeUser?.userId ?? ''
                      });
                    },
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  PostMenuItem(
                    icon: curPost.isLike
                        ? Assets.icons.iconPostLike.image()
                        : Assets.icons.iconLikeGray.image(),
                    title: 'Like',
                    onTap: () {
                      ref
                          .read(afHomePostListServiceProvider.notifier)
                          .toggleLike(item.uid ?? 0);
                    },
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  PostMenuItem(
                    icon: Assets.icons.iconGfitBtn.image(),
                    title: 'Gift',
                    onTap: () {
                      final homeUser = curPost.cacheBind?.homeUser;
                      if (homeUser != null) {
                        showPostGiftSheetView(context, homeUser: homeUser);
                      }
                    },
                  )
                ],
              ),
            ],
          ),
          const SizedBox(
            height: 20,
          ),
        ],
      ),
    );
  }
}

class PostMenuItem extends StatelessWidget {
  const PostMenuItem({
    Key? key,
    required this.title,
    this.onTap,
    required this.icon,
  }) : super(key: key);
  final String title;
  final Function()? onTap;
  final Widget icon;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 3),
        child: Row(
          children: [
            SizedBox(
              width: 18,
              child: Align(
                alignment: Alignment.center,
                child: icon,
              ),
            ),
            const SizedBox(
              width: 5,
            ),
            Text(
              title,
              style: TextStyle(
                color: const Color(0xff000000).withOpacity(0.5),
                fontWeight: FontWeight.normal,
                fontSize: 12,
              ),
              textAlign: TextAlign.center,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            )
          ],
        ),
      ),
    );
  }
}

class PostCommentCell extends StatelessWidget {
  const PostCommentCell({
    Key? key,
    required this.item,
    required this.onClickLike,
  }) : super(key: key);

  final AfPostCommentModel item;

  final Function(AfPostCommentModel item) onClickLike;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xffF8F8F8),
        borderRadius: BorderRadius.circular(16),
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  SizedBox(
                    height: 38,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(19),
                      child: AspectRatio(
                        aspectRatio: 1,
                        child: CachedNetworkImage(
                          imageUrl: item.userInfo?.avatarUrl ?? '',
                          fit: BoxFit.fill,
                          placeholder: (context, url) => const Material(
                            color: Color(0xffF2F5F9),
                            child: Center(
                              child: SizedBox(
                                width: 25,
                                height: 25,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  color: Color(0xffADADAD),
                                  backgroundColor: Colors.white,
                                ),
                              ),
                            ),
                          ),
                          errorWidget: (context, url, error) =>
                              const CircularProgressIndicator(
                            strokeWidth: 2,
                            color: Color(0xffADADAD),
                            backgroundColor: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Text(
                    item.userInfo?.nickname ?? '',
                    style: const TextStyle(
                      color: Color(0xff404040),
                      fontWeight: FontWeight.w500,
                      fontSize: 14,
                    ),
                    textAlign: TextAlign.left,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  )
                ],
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  onClickLike.call(item);
                },
                child: Padding(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
                  child: item.isLike
                      ? Assets.icons.iconPostLike.image(width: 20)
                      : Assets.icons.iconLikeGray.image(width: 20),
                ),
              ),
            ],
          ),
          const SizedBox(
            height: 10,
          ),
          Align(
            alignment: Alignment.topLeft,
            child: Text(
              item.content,
              style: const TextStyle(
                color: Color(0xff404040),
                fontWeight: FontWeight.normal,
                fontSize: 12,
              ),
              textAlign: TextAlign.left,
            ),
          )
        ],
      ),
    );
  }
}
